<!-- tabs组件 -->
<template>
	<scroll-view class="scroll" scroll-x='true' scroll-with-animation :scroll-left='scrollLeft'>
		<view v-for="(item,index) in tablist" :key="index" @click="swichMenu(index)" class="scroll-item"
			:class=" currentTab==index ? 'scroll-item-key' : ''">
			{{item}}
		</view>
	</scroll-view>
</template>

<script setup lang="ts">
	import { ref, defineEmits, watch, getCurrentInstance } from "vue"

	const appInstance = getCurrentInstance().proxy
	const emit = defineEmits(['tabsClick'])

	const props = defineProps({
		tablist: {
			type: Array,
			default: function () {
				return [];
			}
		},
		currentTab: {
			type: Number,
			default: 0
		},
	})
	const scrollLeft = ref(0)  //滚动位置

	watch(
		() => props.currentTab,
		(newProps : number) => { moveTo(newProps) }
	)

	function swichMenu(index : number) {
		emit('tabsClick', index)
	}

	// 将点击元素移动到中间
	function moveTo(index : number) {
		const query = uni.createSelectorQuery().in(appInstance)
		query.selectAll(`.scroll-item`).boundingClientRect(rect => { //拿到每一个tabs标签
			const { windowWidth } = uni.getSystemInfoSync(); //获取屏幕宽度
			let width = 0
			// 循环获取计算当前点击的标签项距离左侧的距离
			for (let i = 0; i < index; i++) {
				width += rect[i].width
			}
			// 当大于屏幕一半的宽度则滚动，否则就设置位置为0
			if (width > windowWidth / 2) {
				scrollLeft.value = width + rect[index].width - windowWidth / 2
			} else {
				scrollLeft.value = 0
			}
		}).exec()
	}
</script>

<style lang="scss" scoped>
	.scroll {
		width: 100%;
		white-space: nowrap; //标签不换行

		.scroll-item {
			display: inline-block;
			padding: 10px 0 5px;
			margin: 0 10px;
			font-size: 30rpx;
			color: #666;
		}

		.scroll-item-key {
			font-weight: 600;
			color: #007bff;
			border-bottom: 2px solid #007bff;
		}
	}

	.scroll ::v-deep ::-webkit-scrollbar {
		//隐藏scroll-view里面自带的滚动条
		display: block; //必加
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: auto !important;
		background: transparent;
		overflow: auto !important;
	}
</style>